<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
</head>

<body>
	<a href="/">首页</a>
	<a href="/about">about</a>

	<div class="routerview">

	</div>

	<script>
		let routerView = [
			{
				path: "/",
				content: "<div>首页</div>"
			}, {
				path: "/about",
				content: "<div>about</div>"
			}
		]


		window.addEventListener("DOMContentLoaded", () => {
			// 获取所有的a标签
			var linklist = document.querySelectorAll("a[href]");
			linklist.forEach((item) => {
				item.addEventListener('click', (e) => {
					// 取消a标签的默认事件（页面跳转）
					e.preventDefault()
					// console.log("a标签的点击事件")
					history.pushState(null, "", item.getAttribute("href"))
					RouterRender(item.getAttribute('href'))
				})
			})
		})



		history.pushState(null, "", "/")
		RouterRender("/")

		function RouterRender(url) {
			var resContent;
			routerView.forEach((item, i) => {
				if (url == item.path) {
					resContent = item.content;
				}
			})

			let divRouterView = document.querySelector('.routerview');
			divRouterView.innerHTML = resContent;

		}


		window.addEventListener('popstate', () => {
			console.log(location.pathname)
			RouterRender(location.pathname)
		})



	</script>
</body>

</html>